import * as region from '@/static/data/regions.json'
import {
	ref,
	computed
} from 'vue'


const useArea = (cb) => {

	const areaPicker = ref()
	const province = ref([])
	const citys = ref([])
	const areas = ref([])
	const pickerValue = ref([0, 0, 0])
	const defaultValue = ref([3442, 1, 2])
	const prevIndex = ref(0)
	province.value = region.default.sort((left, right) => (Number(left.code) > Number(right.code) ? 1 : -1));

	const addressList = computed(() => {
		return [province.value, citys.value, areas.value];
	})

	handlePickValueDefault()

	function handlePickValueDefault() {
		// 设置省
		pickerValue.value[0] = province.value.findIndex(item => Number(item.id) === defaultValue.value[0]);
		console.log('pickerValue:', pickerValue.value)
		// 设置市
		citys.value = province.value[pickerValue.value[0]]?.children || [];


		pickerValue.value[1] = citys.value.findIndex(item => Number(item.id) === defaultValue.value[1]);
		// 设置区
		areas.value = citys.value[pickerValue.value[1]]?.children || [];
		pickerValue.value[2] = areas.value.findIndex(item => Number(item.id) === defaultValue.value[2]);
		// 重置下位置
		areaPicker.value?.setIndexs([pickerValue.value[0], pickerValue.value[1], pickerValue.value[2]]);
	}

	function areaChange(e) {

		const {
			columnIndex,
			index
		} = e
		// 改变了省
		if (columnIndex === 0) {
			prevIndex.value = index;
			citys.value = province.value[index]?.children || []
			areas.value = citys.value[0]?.children || []
			areaPicker.value?.setIndexs([index, 0, 0])
		} else if (columnIndex === 1) {
			areas.value = citys.value[index]?.children || []
			areaPicker.value.setIndexs([prevIndex.value, index, 0])
		}
	}

	function open() {
		console.log('open area')
		areaPicker.value.open();
		handlePickValueDefault()
	}

	function areaConfirm(e) {
		console.log('确认选择的地区：', e);
		// 北京市-北京市-东城区
		let str = []
		e.value.forEach(item => {
			str.push(item.name)
		})

		cb(str.join('-'))

	}

	return [areaPicker, addressList, areaChange, areaConfirm, open]

}

export default useArea;